package com.qfedu.web;

import cn.hutool.core.date.DateUtil;
import com.qfedu.entity.User;
import com.qfedu.service.UserService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    @RequestMapping("/register")
    public String Register(User user, MultipartFile userImg, HttpSession session) throws IOException {
        user.setRegisterTime(DateUtil.now());
        System.out.println(user);

        //文件原始名称
        String filename = userImg.getOriginalFilename();
        System.out.println(filename);
        //定制全局唯一命名
        String unique = UUID.randomUUID().toString();

        //获得文件后缀
        String ext = FilenameUtils.getExtension(filename);

        //定制全局唯一文件名
        String uniqueFileName = unique + "." +ext;
        System.out.println("唯一的文件名：" + uniqueFileName);

        //文件的类型
        String type = userImg.getContentType();
        System.out.println("filename:" + filename + "type:" + type);

        String real_path = session.getServletContext().getRealPath("/upload");
        System.out.println("real_path:"+real_path);
        File file = new File(real_path);
        if (!file.exists()) {
            file.mkdirs();
        }

        //将上传的文件，存入磁盘路径中
        //source.transferTo(new File("d:/xxxx/xxxx/xx.jpg"))
        userImg.transferTo(new File(real_path+"\\"+uniqueFileName));
        String imgUrl = "target\\FirstSSM-1.0-SNAPSHOT\\upload" + uniqueFileName;
        user.setImgUrl(imgUrl);
        userService.register(user);
        return "registerSuccess";
    }

    @RequestMapping("/login")
    public String Login(String username, String password, HttpServletRequest request){
        System.out.println(username + "\t" +password);
        User user = userService.selectUser(username, password);
        if (user != null){
            HttpSession session = request.getSession();
            session.setAttribute("state","ok");
            return "index";
        }
        return "loginFail";
    }

    @RequestMapping("/select")
    @ResponseBody
    public List<User> selectUser(){
        List<User> list = userService.selectAllUser();
        for (User user : list){
            System.out.println(user);
        }
        return list;
    }
}
